package logic

import (
	"context"
	"errors"
	"zhongwen/cache"
	"zhongwen/models/mysql"
	"zhongwen/pkg"

	"zhongwen/zhongwenrpc/internal/svc"
	"zhongwen/zhongwenrpc/zhongwenrpc"

	"github.com/zeromicro/go-zero/core/logx"
)

type LoginLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewLoginLogic(ctx context.Context, svcCtx *svc.ServiceContext) *LoginLogic {
	return &LoginLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *LoginLogic) Login(in *zhongwenrpc.LoginRequest) (*zhongwenrpc.LoginResponse, error) {
	// todo: add your logic here and delete this line

	result, _ := cache.Rdb.Get(cache.Ctx, "sendSms"+in.Mobile).Result()
	if result != in.SendSms {
		return nil, errors.New("验证码错误请重新输入")
	}
	var user mysql.User
	mysql.DB.Debug().Where("mobile=?", in.Mobile).Find(&user)
	if user.ID == 0 {
		user = mysql.User{
			Mobile:   in.Mobile,
			Password: pkg.Md5Str(in.Password),
		}
		mysql.DB.Debug().Create(&user)
	} else {
		if user.Password != pkg.Md5Str(in.Password) {
			return nil, errors.New("密码错误")
		}
	}

	return &zhongwenrpc.LoginResponse{
		UserId: int64(user.ID),
	}, nil
}
